package top.chenyaohua.utils;

import top.chenyaohua.visitorImp.ClassFileVisitor;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtils {

    /**
     * 获取目录下的文件
     * @param uri
     * @return
     */
    public static List<File> getFileList(URI uri,String pack){

        ClassFileVisitor classFileVisitor = getClassFileVisitor(uri, pack);

        return classFileVisitor.getFiles();
    }

    /**
     * 获取目录下的文件
     * @param uri
     * @return
     */
    public static List<String> getClassNames(URI uri, String pack){

        ClassFileVisitor classFileVisitor = getClassFileVisitor(uri, pack);

        List<Path> paths = classFileVisitor.getPaths();
        List<String> collect = paths.stream().map(x -> Paths.get(uri).relativize(x).toString().replace("\\",".").replace(".class","")).collect(Collectors.toList());

        return collect;
    }


    private static ClassFileVisitor getClassFileVisitor(URI uri, String pack){

        Path path = Paths.get(uri);
        //包路径
        Path packPath = Paths.get("./" + pack.replace(".", "/"));
        //解析后包的文件目录
        Path normalize = path.resolve(packPath).normalize();

        ClassFileVisitor classFileVisitor = new ClassFileVisitor();
        try {
            Files.walkFileTree(normalize, classFileVisitor);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  classFileVisitor;
    }
}
